<template>
<div id="post">

    <md-dialog :md-active.sync="showDialog">
        <md-dialog-title>截取头像</md-dialog-title>

        <vue-croppie class="croppie" ref="croppieRef" :enableOrientation="true" :enableResize="true" :viewport="{ width:300, height:300, type:'circle' }">
        </vue-croppie>
        <md-dialog-ations>
            <md-button class="md-primary" @click="showDialog = false">取消</md-button>
            <md-button class="md-raised md-primary" @click="crop">上传</md-button>
        </md-dialog-ations>

    </md-dialog>

    <div class="container">
        <div id="user">
            <img :src="current_user.avatar" alt="" id="avatar" @click="$refs.avatar.click()">
            <input ref="avatar" v-show="false" type="file" @change="croppie" />

            <md-field>
                <label>Say Something</label>
                <md-textarea v-model="article" md-autogrow></md-textarea>
            </md-field>
        </div>

        <div id="operation">
            <md-progress-bar v-if="showProgress" md-mode="determinate" :md-value="progress"></md-progress-bar>
            <input type="file" @change="getImgUrl" accept="image/*" ref="imgSelect" style="display:none">
            <md-button class="md-raised md-primary" @click="$refs.imgSelect.click()">选择图片</md-button>
            <md-button :disabled="canPost" class="md-raised md-primary" @click="post">发布</md-button>
        </div>

        <b-row>

            <b-col>
                <b-img-lazy thumbnail v-bind="mainProps" :src="articleImg" v-if="!!articleImg" fluid alt="预览图片"></b-img-lazy>
            </b-col>
            <b-col></b-col>

        </b-row>

    </div>

    <div class="all-posts">
        <post v-for="post in posts" :key="post.id" :post="post" />
    </div>

    <div id="load">
        <md-button class="md-raised md-primary" @click="load" v-show="canLoad">加载更多</md-button>
        <div id="alert"><b-alert :show="loadAlert" variant="danger">{{loadFailMsg}}</b-alert></div>
    </div>
    
</div>
</template>

<script>
// @ is an alias to /src
import postApi from '../api/post'
import post from './Post'
export default {
    name: 'Posts',
    components: {
        post
    },
    data() {
        return {
            // canPost:false,
            canLoad:true,
            loadFailMsg:'加载失败',
            loadAlert:false,
            showDialog: false,
            croppieImage: '',
            cropped: null,
            mainProps: {
                center: true,
                fluidGrow: true,
                blank: true,
                blankColor: '#bbb',
                width: 'auto',
                height: 'auto',
                class: 'my-5'
            },
            progress: 0,
            showProgress: false,
            imgFile: null,
            articleImg: '',
            article: '',
            user: {
                id: '123',
                username: 'wzq',
                avatar: '',
            },
            me: {
                id: '123',
                username: '',
                avatar: '',
            },
            posts: [],

        }
    },
    created() {
        postApi.getPost().then(res => {
            this.posts = res.data;
        }).catch(err => {
            window.console.log(err.response);
        })
    },
    watch:{
        // canPost
    },
    mounted() {
        let title = '';
        if (this.user.id === this.me.id)
            title = "个人中心";
        else
            title = `${this.user.username}的主页`;
        document.title = title;

        if (!this.current_user.avatar) {
            this.current_user.avatar = require('../assets/avatar.jpg')
        }

    },
    computed: {
        current_user() {
            return this.$store.state.user;
        },
        offset(){
            return this.posts.length;
        },
        canPost:{
            
            get(){
                return this.articleImg===''&&this.article===''
            },
            set(){
                
            },
        }
       
    },
    methods: {
        load(){
            window.console.log(this.offset)
            postApi.getPost({params:{offset:this.offset}}).then(res=>{
                this.posts = this.posts.concat(res.data)
                if(!res.data.length){
                    this.loadAlert = true
                    this.loadFailMsg = '我是有底线的！'
                    this.canLoad = false
                }
            }).catch(err=>{
                this.loadAlert = true
                this.loadFailMsg = err.message
            })
        },
        crop() {
            // Options can be updated.
            // Current option will return a base64 version of the uploaded image with a size of 600px X 450px.
            let options = {
                type: 'base64',
                circle: true,
                size: {
                    width: 300,
                    height: 300
                },
                format: 'jpeg'
            };
            this.$refs.croppieRef.result(options, output => {
                this.cropped = this.croppieImage = output;
                window.console.log(this.croppieImage);
            });
        },
        croppie(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;

            var reader = new FileReader();
            reader.onload = e => {
                this.$refs.croppieRef.bind({
                    url: e.target.result
                });
            };

            reader.readAsDataURL(files[0]);
            this.showDialog = true;
        },
        getImgUrl(e) {
            let file = e.target.files[0];
            this.imgFile = file;
            if (!file)
                return;

            this.tools.getOrientation(file, (orientation) => {
                window.console.log(orientation);
            })

            let reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onloadstart = () => {

                this.showProgress = true;
            }
            reader.onprogress = (res) => {

                this.progress = (res.loaded / res.total).toFixed(2) * 100;

            }
            reader.onload = () => {
                this.showProgress = false;
                this.articleImg = reader.result.toString();
                this.progress = 0;
            }
        },
        post() {
            this.canPost = true
            // if (!this.article) {
            //     alert('请输入您要发表的文字！');
            //     return;
            // }
            const user = this.current_user;
            const newPost = {
                user: {
                    id: user.id,
                    username: user.username,
                    userAvatar: user.avatar,
                },
                content: this.article,
                img: this.articleImg,
                like: [],
                date: Date.now(),
                comments: []
            };
            postApi.submitsPost(newPost).then(res => {
                window.console.log(res);
                this.posts.unshift(newPost);
                this.article = '';
                this.articleImg = "";
                this.canPost = false
                
            }).catch(err => {
                window.console.log(err.response)
                this.canPost = false
                
            })
        },

    }
}
</script>

<style lang="scss" scoped>
$mobile-width:600px;

.croppie {
    margin-bottom: 5vh;
}

#user {
    display: flex;
}

#avatar {
    width: 5vmax;
    height: 5vmax;
    border-radius: 50%;
    margin-right: 1vmax;
    outline: none;
    cursor: pointer;
}

#operation {
    margin-left: 6vmax;
}

.all-posts {
    margin: 0 auto;
    width: 96vw;
}

.md-dialog {
    padding: 1rem 2rem;
}

#load{
    display: flex;
    justify-content: center;

    // align-items: center;
    #alert{
        margin:1vh 1vw;
    }
}



@media (min-width: $mobile-width) {

    .all-posts {
        width: 50vw;

    }

    .md-dialog {
        width: 40vw;
        height: 60vh;
    }
}
</style>
